import { IMCONFIG } from '@/constants';

import { genTestUserSig } from '@/utils/im/GenerateTestUserSig';
import TencentCloudChat, { ChatSDK } from '@tencentcloud/chat';
import '@tencentcloud/chat-uikit-react/dist/cjs/index.css';
import { history } from '@umijs/max';
import { message } from 'antd';
import { useState } from 'react';
import TIMUploadPlugin from 'tim-upload-plugin';
const useTencentIm = () => {
    const [chat, setChat] = useState<ChatSDK>();
    // create chat instance && login
    const init = async (mobile: string): Promise<ChatSDK> => {
        return new Promise((resolve, reject) => {
            if (!mobile) {
                reject();
                return
            }
            const chat = TencentCloudChat.create({
                SDKAppID: IMCONFIG.IM_SDKAppID,
            }); // Your SDKAppID,参考步骤4获取
            chat.setLogLevel(4);
            chat.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
            const onReady = () => {
                resolve(chat);
            };
            chat.on(TencentCloudChat.EVENT.SDK_READY, onReady);
            const config = {
                userID: IMCONFIG.PERFIX + mobile, //User ID
                SDKAppID: IMCONFIG.IM_SDKAppID, // Your SDKAppID
                secretKey: IMCONFIG.IM_secretKey, // Your secretKey
            };
            // UserSig 是用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文，参考步骤4获取
            chat.login({
                userID: IMCONFIG.PERFIX + mobile,
                userSig: genTestUserSig(config).userSig,
            });
        });
    };
    const createC2CConversation = (mobile: string, currentMobile: string, iskf?: boolean) => {
        return new Promise((resolve, reject) => {
            if (!mobile) {
                return;
            }
            if (currentMobile === mobile) {
                reject()
                return
            }
            if(!chat){
                reject(1)
            }
            // 聊天的userID
            const userID = iskf === true ? IMCONFIG.kfs[0] : IMCONFIG.PERFIX + mobile;
            const conversationID = `C2C${userID}`;
            chat.getConversationProfile(conversationID)
                .then((res) => {
                    console.log('createC2CConversation-success', res)
                    history.push('/message/im',{conversationID})
                    // chat.switchConversation(
                    //     res.data.conversation.conversationID
                    // );
                    // uni.navigateTo({
                    //     url: '/TUIKit/components/TUIChat/index'
                    // });
                })
                .catch((err) => {
                    console.warn("打开会话失败", err.code, err.msg);
                });
            resolve(1)
        })
    }
    return {
        init,
        chat,
        setChat,
        createC2CConversation,
    };
}
export default useTencentIm;
